<?php 
namespace BLL\DAO;

use BLL\DataModel as DM;
use Exception;
/*
 *  
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2015 Max Group. All rights reserved.
 * 
 */

/**
 * Description of TableHelper
 *
 * @author david
 */
class TableBuilder {

    static $adapter = null;

    public static function createTable(DM\DataNodeDescription $model, $silent =true, $inTrans = false) {
        if (self::$adapter) {
            return false;
        }
        self::$adapter = new DataModelBuiltTableAdapter($model);
        $tableName = $model->getRealTableName();
        if (!$inTrans) {
            \DB::beginTransaction();
        }
        try {
            if (\Schema::hasTable($tableName)) {
                if (!$silent) {
                    throw new Exception("Table Already Exist:$tableName");
                }
                \Log::info("Table {$tableName} already exist. ");
            }
            else{
                \Schema::create($tableName, function($table) {
                    static::$adapter->builtTable($table);
                    $table->timestamps();
                });
               \Log::info("Table {$tableName} created. ");
            }
            self::$adapter = null;
            foreach ($model->nodes as $node) {
                self::createTable($node, $silent , true);
            }
            if (!$inTrans) {
                \DB::commit();
            }
        } catch (Exception $e) {
            self::$adapter = null;
            \DB::rollback();
            throw $e;
        }
        return true;
    }


}
